<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="DiaTitle"
    width="30%"
    :before-close="handleClose"
  >
    <el-form :model="Roleform" ref="formRef" :rules="rules">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="Roleform.roleName" />
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="Roleform.roleDesc" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="CancelAdd">取消</el-button>
        <el-button type="primary" @click="ConfirmAdd">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, defineProps, reactive, shallowReactive, watch } from "vue";
import { ElMessage } from "element-plus";
import apis from "@/http/apis";

let Props = defineProps({
  dialogVisible: Boolean, //是否显示
  DiaTitle: String, //弹窗标题
  EditData: {
    type: Object,
    default: {},
  }, //编辑需用到的当前对象
});
const formRef = ref(); //定义表单的ref实例，在提交之后掉ref的表单验证方法

let Roleform = reactive({
  roleName: "",
  roleDesc: "",
});

//监听当前对象的变化
watch(
  () => Props.EditData, //新值
  () => {
    //监听输入的值的变化将当前的对象赋给form
    Roleform = Props.EditData as any;
    console.log(Roleform.roleName);
  },
  {
    //处理函数
    deep: true,
    immediate: true,
  }
);
//定义发布事件实例
const emits = defineEmits(["update:modelValue", "initRolelist"]);

//关闭处理函数
const handleClose = () => {
  emits("update:modelValue", false);
};
//取消处理函数
const CancelAdd = () => {
  handleClose();
};
//确实处理函数
const ConfirmAdd = async () => {
  //表单验证
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      Props.DiaTitle === "添加用户"
        ? await apis.addRoleList(Roleform)
        : await apis.EditRole(Roleform);
      emits("initRolelist"); //发送事件让父组件刷新数据
      ElMessage({
        message: "添加用户成功",
        type: "success",
      });
      handleClose();
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

//表单校验规则
const rules = shallowReactive({
  roleName: [
    {
      required: true,
      message: "请您填写用户名",
      trigger: "blur",
    },
  ],
  roleDesc: [
    {
      required: true,
      message: "请填写描述",
      trigger: "blur",
    },
  ],
});
</script>

<style lang="less" scoped></style>
